const express = require(`express`)
const asyncHandler = require('express-async-handler');
const userCtrl = require('../controllers/user.controller') 
const passport = require('passport');

const router = express.Router()

router.post('/login', passport.authenticate('local', { session: false }), login);
router.post('/register', asyncHandler(register));
router.post('/logout', asyncHandler(logout));
router.get('/info', passport.authenticate('jwt', { session: false }), info);

// 登录
async function login(req, res){
    const user = req.user
    let token = userCtrl.generateToken(user)
    res.json({
        code: 20000,
        data: {token:token}
    })
}

// 获取用户信息
async function info(req, res){
    // jwt 拦截里面获取到了用户信息
    const user = req.user
    res.json({
        code: 20000,
        data: user
    })
}

// 退出登录
async function logout(req, res){
    res.json({
        code: 20000,
        data: '退出登录'
    })
}


// 注册
async function register(req, res, next){
    // 检查用户是否存在
    let data = await userCtrl.findByUsername(req.body.username)
    if (data) {
        res.json({
            code: -1,
            message: '当前用户已经注册'
        })
        return
    }
    // 注册
    const user = await userCtrl.insert(req.body);
    res.json({
        code: 20000,
        message: '注册成功'
    })
}

module.exports = router